/*

* ------------------------------------------------------------------------
* ------------------------------------------------------------------------
* |     Smart-Shop开源商城系统/ Java商城-首选电商平台系统 请务必保留此注释头信息
* |     开源地址: https://gitee.com/ningbo-qishan/gruul-mall
* ------------------------------------------------------------------------
* ------------------------------------------------------------------------
* |     可正常分享和学习源码,未经授权 不可商用！
* |     商业版中台购买/开源版商业授权 联系技术客服
* |     官网:  https://www.73app.cn/
* ------------------------------------------------------------------------
* ------------------------------------------------------------------------
* |     Copyright (c) 2016-2999 宁波启山智软科技有限公司
* |     版权所有 ,侵权必究！
* ------------------------------------------------------------------------

*/
package com.medusa.gruul.solitaire.web.utils.http;


import lombok.extern.slf4j.Slf4j;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;

import javax.net.ssl.*;

/**
 * OkHttp SSL 工具类
 */
@Slf4j
public class OkHttpUtil {

	/**
	 * Setting testMode configuration. If set as testMode, the connection will skip certification check
	 *
	 * @param builder
	 * @return
	 */
	public static OkHttpClient.Builder configureToIgnoreCertificate(OkHttpClient.Builder builder) {
		log.warn("Ignore Ssl Certificate");
		try {
			/*Create a trust manager that does not validate certificate chains*/
			final TrustManager[] trustAllCerts = new TrustManager[]{
					new X509TrustManager() {
						@Override
						public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) {
						}

						@Override
						public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) {
						}

						@Override
						public java.security.cert.X509Certificate[] getAcceptedIssuers() {
							return new java.security.cert.X509Certificate[]{};
						}
					}
			};

			/*Install the all-trusting trust manager*/
			final SSLContext sslContext = SSLContext.getInstance("SSL");
			sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
			/*Create an ssl socket factory with our all-trusting manager*/
			final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();

			builder.sslSocketFactory(sslSocketFactory, (X509TrustManager) trustAllCerts[0]);
			builder.hostnameVerifier(new HostnameVerifier() {
				@Override
				public boolean verify(String hostname, SSLSession session) {
					return true;
				}
			});
		} catch (Exception e) {
			log.warn("Exception while configuring IgnoreSslCertificate" + e, e);
		}
		return builder;
	}

	public static OkHttpClient client(Interceptor interceptor) {
		OkHttpClient.Builder builder = new OkHttpClient.Builder();
		OkHttpUtil.configureToIgnoreCertificate(builder);
		if (interceptor != null) {
			builder.addInterceptor(interceptor);
		}
		return builder.build();
	}

}